package com.bjpower.utlis;

import com.bjpower.common.mail.Attachment;
import com.bjpower.common.mail.MailProperty;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MailUtil {
    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 发送简单邮件的方法
     * @return
     */
    public Boolean sendSimpleMail(MailProperty mailProperty){
        System.out.println("开始发送邮件");
        Boolean send = false;
        //创建邮件对象
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(mailProperty.getFrom());
            message.setTo(mailProperty.getTo());
            message.setSubject(mailProperty.getSubject());
            message.setText(mailProperty.getContent());
            javaMailSender.send(message);
            send = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return send;
    }
    /**
     * 发送发杂邮件的方法
     */
    public Boolean sendMimeMail(MailProperty mailProperty){
        Boolean send = false;
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(mailProperty.getFrom());
            messageHelper.setTo(mailProperty.getTo());
            messageHelper.setSubject(mailProperty.getSubject());
            messageHelper.setText(mailProperty.getContent());
            //遍历附件
            List<Attachment> attachments = mailProperty.getAttachments();
            for (Attachment attachment : attachments) {
                messageHelper.addAttachment(attachment.getFileName(),attachment.getFilePath());
            }
            javaMailSender.send(messageHelper.getMimeMessage());
            send = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return send;
    }
}
